package com.atguigu.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchClientConfig {
    @Value("${elasticsearch.cluster-nodes}")
    private String nodes;
    @Value("${elasticsearch.scheme-name}")
    private String scheme;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        String nodesStringWithoutSpace = nodes.replace(" ", "");
        String[] ips = nodesStringWithoutSpace.split(",");
        HttpHost[] hosts = new HttpHost[ips.length];
        for (int i = 0; i < ips.length; i++) {
            String[] ipSplit = ips[i].split(":");
            hosts[i] = new HttpHost(ipSplit[0], Integer.parseInt(ipSplit[1]), scheme);
        }
        return new RestHighLevelClient(RestClient.builder(hosts));
    }
}